import type { TabsStoreType } from "@/typings/stores";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { createJSONStorage, devtools, persist } from "zustand/middleware";
import { getUrlWithParams } from "@/utils";
import { useNavigateCacheRouter } from "@/hooks/modules/useRouter";

const initialState: TabsStoreType.stateType = {
  tabsList: []
};

const actions = (set: TabsStoreType.settersStoreType) => {
  const setTabsList = (payload: TabsStoreType.TabsListProp[]) => {
    set((state: TabsStoreType.stateType) => {
      state.tabsList = payload;
    });
  };

  const addTab = (payload: TabsStoreType.TabsListProp) => {
    set((state: TabsStoreType.stateType) => {
      if (state.tabsList.every((item) => item.path !== payload.path)) {
        state.tabsList.push(payload);
        return;
      }
      state.tabsList = state.tabsList.flatMap((item) => (item.path === payload.path ? [{ ...item, ...payload }] : [item]));
    });
  };

  const removeTab = (payload: { path: string; isCurrent: boolean }) => {
    set((state: TabsStoreType.stateType) => {
      if (!state.tabsList.find((item) => item.path === payload.path)?.closable) {
        return;
      }
      if (payload.isCurrent) {
        const { getNavigateCache } = useNavigateCacheRouter();
        state.tabsList.forEach((item, index) => {
          if (item.path !== payload.path) return;
          const nextTab = state.tabsList[index + 1] || state.tabsList[index - 1];
          if (!nextTab) return;
          getNavigateCache(nextTab.path);
        });
      }
      state.tabsList = state.tabsList.filter((item) => item.path !== payload.path);
    });
  };

  const closeTabsOnSide = (payload: { path: string; type: "left" | "right" }) => {
    set((state: TabsStoreType.stateType) => {
      const currentIndex = state.tabsList.findIndex((item) => item.path === payload.path);
      if (currentIndex !== -1) {
        const range = payload.type === "left" ? [0, currentIndex] : [currentIndex + 1, state.tabsList.length];
        state.tabsList = state.tabsList.filter((item, index) => {
          return index < range[0] || index >= range[1] || !item.closable;
        });
      }
    });
  };

  const closeMultipleTab = (payload: { path?: string }) => {
    set((state: TabsStoreType.stateType) => {
      state.tabsList = state.tabsList.filter((item) => item.path === payload.path || !item.closable);
    });
  };

  const setTabTitle = (payload: string) => {
    set((state: TabsStoreType.stateType) => {
      state.tabsList = state.tabsList.map((item) => {
        if (item.path == getUrlWithParams()) return { ...item, title: payload };
        return item;
      });
    });
  };

  return { setTabsList, addTab, removeTab, closeTabsOnSide, closeMultipleTab, setTabTitle };
};

const devtoolsConfig = { name: "REACT_APP_TABS_STORAGE", enabled: import.meta.env.VITE_APP_REDUX_DEVTOOLS === "true" };
const persistConfig = { name: "REACT_APP_TABS_STORAGE", storage: createJSONStorage(() => localStorage) };
export const useTabsStore = create<TabsStoreType.storeType>()(
  devtools(
    persist(
      immer((set) => ({
        ...initialState,
        ...actions(set)
      })),
      persistConfig
    ),
    devtoolsConfig
  )
);
